#-------------------------------------------------------------------------------
# Name:        generate_jsons_error
# Purpose:     This script generates JSON files with dict of values for creating
#              mappanalysis.ProgramVariables and saves it to the selected directory.
#
# Author:      Bc. Ondrej Pelikan
#
# Created:     23.04.2013
#-------------------------------------------------------------------------------


import argparse
# from utils import addDirToSysPath
# addDirToSysPath("../") #relative path to parent folder of mappanalysis package
import mappanalysis
import json
import os
import re


def main():
    #parse args
    parser = argparse.ArgumentParser(description='generates JSON representations of mappanalysis.ProgramVariables and saves it to the selected directory.')
    parser.add_argument('-d', '--output', default="prog_vars", type=str, help='Path to the directory where json files will be generated.', dest='dir')
    parser.add_argument('-f', '--expfrom', default=-100, type=int, help='From what exponent of error it should be start.', dest='frm')
    parser.add_argument('-t', '--expto', default=0, type=int, help='To what exponent of error are json files generated.', dest='to')
    parser.add_argument('-s', '--expstep', default=1, type=int, help='The step between two exponents of error.', dest='step')
    parser.add_argument('-i', '--input', default="lacI.seq", type=str, help='File with input sequence in fasta format', dest='input')
    parser.add_argument('-m', '--mutations', default="lacI_deleterious.muts", type=str, help='File with somehow delimited mutations in format letternumberletter', dest='mut')
    parser.add_argument('-o', '--outprefix', default="del_", type=str, help='Prefix for names ofoutput files.', dest='prefix')
    args = parser.parse_args()
    outdir = args.dir
    expfrom = args.frm
    expto = args.to
    expstep = args.step
    seqfile = args.input
    mutfile = args.mut
    prefix = args.prefix

    #get sequence
    openedInFile = open(seqfile, "r")
    sequence = getSequenceFromFasta(openedInFile.read())
    openedInFile.close()

    #get mutations
    openedInFile = open(mutfile, "r")
    mutations = mappanalysis.parseMutations(openedInFile.read())
    openedInFile.close()

    #generate ProgramVariables files
    for exp in range(expfrom, expto, expstep):
        d = {"sequence"     : sequence,
             "mutations"    : mutations,
             "database"     :  "nr",
             "error"        : "1e" + str(exp),
             "tree_method"  : "nj",
             "filename"     : "error" + str(exp)}
        openedInFile = open(os.path.join(outdir, prefix + "error_" + str(exp) + ".json"), "w")
        openedInFile.write(json.dumps(d))
        openedInFile.close()



def getSequenceFromFasta(fasta):
    return re.match(">.+\n(.+)", fasta).group(1)

if __name__ == '__main__':
    main()
